package com.pudu.mydemo.act;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.pudu.mydemo.entity.FileUpload;
import com.pudu.mydemo.utils.UpdateManager;
import com.pudu.mydemo.utils.WiFi;
import com.pudu.mydemo.view.TastyToast;
import com.pudu.pdrobot.App;
import com.pudu.pudusclient.ControlServiceService;
import com.pudutech.pdrobot.R;

import java.util.Calendar;


public class HomeActivity extends BaseHomeActivity implements View.OnTouchListener{
    private ImageButton smart_cruise, go_back, setting,through;
    private ImageButton zhuye;
    private RelativeLayout center;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化广播，开启定时任务，用于每天的日志上传
        FileUpload fp = new FileUpload();
        fp.onTimePost(this);
        checkUpdate();

        if(Welcome.mapSet())
        {
            StartControlService();
        }
    }

    public void StartControlService()
    {
        Intent bindingIntent = new Intent(this, ControlServiceService.class);
        startService(bindingIntent);
        bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        try{
            this.unbindService(serviceConnection);
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private final ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            App.instance.myService = ((ControlServiceService.ServiceBinder) service).getService();

            Log.i(App.MYTAG, "onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            //onServiceDisconnected is only called in extreme situations (crashed / killed).
            Log.i(App.MYTAG, "onServiceDisconnected");
        }

    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }


    @Override
    protected void onResume() {
        super.onResume();

//        UpdateManager updateManager = new UpdateManager(this, false);
//        updateManager.checkUpdate();
    }

    private void checkUpdate() {
        if ( !App.isUpdate) {
            return;
        }
        /*Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                new UpdateManager(HomeActivity.this, false).checkUpdate();
            }
        }, 2000);*/
        new UpdateManager(HomeActivity.this, false).checkUpdate();
    }

    @Override
    public void initView() {
        smart_cruise = (ImageButton)findViewById(R.id.smart_cruise);
        go_back = (ImageButton)findViewById(R.id.goback);
        setting = (ImageButton)findViewById(R.id.setting);
        zhuye=(ImageButton) findViewById(R.id.zhuye);
        through = (ImageButton)findViewById(R.id.through);
        center = (RelativeLayout)findViewById(R.id.center);



    }

    @Override
    public void initEvent() {
        smart_cruise.setOnTouchListener(this);
        through.setOnTouchListener(this);
        go_back.setOnTouchListener(this);
        setting.setOnTouchListener(this);
        /*smart_cruise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, SmartActivity.class);
                startActivity(intent);
//                overridePendingTransition(R.anim.anim_in, R.anim.anim_out);
            }
        });*/
        smart_cruise.setOnClickListener(this);
        through.setOnClickListener(this);
        go_back.setOnClickListener(this);
        setting.setOnClickListener(this);
        zhuye.setOnClickListener(this);

       /* through.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, ThroughActivity.class);
                startActivity(intent);
            }
        });

        go_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, GoBackActivity.class);
                startActivity(intent);
            }
        });

        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, SettingActivity.class);
                startActivity(intent);
            }
        });

        zhuye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, SmailActivity.class);
                startActivity(intent);
               finish();
            }
        });*/


    }

    public abstract class NoDoubleOnclick implements View.OnClickListener{
        public static final int MIN_CLICK_DELAY_TIME = 1000;
        private long lastClickTime = 0;
        @Override
        public void onClick(View v) {
            long currentTime = Calendar.getInstance().getTimeInMillis();
            if(currentTime - lastClickTime > MIN_CLICK_DELAY_TIME ){
                lastClickTime = currentTime;
                onNoDoubleClick(v);
            }
        }

        public abstract void onNoDoubleClick(View v);
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {

             Bitmap bitmap = getBitmap(v.getId());
                if(event.getAction() == MotionEvent.ACTION_DOWN) {
                    if(v.getId() == R.id.smart_cruise) {
                        smart_cruise.setImageBitmap(bitmap);
                        if(!WiFi.isWifiOpen()) {
                           //string 只会获取系统当前语言环境下对应的string
                            TastyToast.makeText(this,this.getString(R.string.wifi_not_connect_not_smart), TastyToast.LENGTH_LONG, getHeight() / 12);
                            return true;
                        }else if(!Welcome.mapSet()){
                            TastyToast.makeText(this,this.getString(R.string.map_not_set), TastyToast.LENGTH_LONG, getHeight() / 12);
                            return true;
                        }
                    } else if(v.getId()== R.id.through) {
                        through.setImageBitmap(bitmap);
                        if(!WiFi.isWifiOpen()) {
                            TastyToast.makeText(this, this.getString(R.string.wifi_not_connect_not_through), TastyToast.LENGTH_LONG,  getHeight() / 12);
                            return true;
                        }
                    } else if(v.getId() == R.id.goback) {
                        go_back.setImageBitmap(bitmap);
                    } else if(v.getId() == R.id.setting) {
                        setting.setImageBitmap(bitmap);
                    }
                    changeLayout();
                } else if(event.getAction() == MotionEvent.ACTION_UP) {
                    if(v.getId() == R.id.smart_cruise) {
                        smart_cruise.setImageDrawable(getResources().getDrawable(R.mipmap.smart_cruise));
                    } else if(v.getId()== R.id.through) {
                        through.setImageDrawable(getResources().getDrawable(R.mipmap.through_mode));
                    } else if(v.getId() == R.id.goback) {
                        go_back.setImageDrawable(getResources().getDrawable(R.mipmap.go_back));
                    } else if(v.getId() == R.id.setting) {
                        setting.setImageDrawable(getResources().getDrawable(R.mipmap.setting));
                    }

                }

        return false;
    }

    public Bitmap getBitmap(int id) {
        int mipmapId = id ;
        if(id == R.id.smart_cruise) {
            mipmapId = R.mipmap.smart_cruise_press;
        } else if(id == R.id.through) {
            mipmapId = R.mipmap.through_mode_press;
        } else if(id == R.id.goback) {
            mipmapId = R.mipmap.go_back_press;
        } else if(id == R.id.setting) {
            mipmapId = R.mipmap.setting_press;
        }
        Bitmap tempBitmap = BitmapFactory.decodeResource(getResources(),mipmapId);
        Bitmap bitmap = Bitmap.createScaledBitmap(tempBitmap,259,280,true);
        return bitmap;
    }
    public void changeLayout() {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) center.getLayoutParams();
        lp.leftMargin = 0;
        lp.rightMargin =0 ;
        center.setLayoutParams(lp);
    }

    @Override
    public void initData() {
        super.initData();
//        Log.e("to","177dp:"+dip2px(getApplicationContext(),177));
//
//        Log.e("to","177dz:"+px2dip(getApplicationContext(),177));
//
//        Log.e("to","17dz:"+px2dip(getApplicationContext(),17));

    }

    public int getHeight() {
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int heightPixels = metric.heightPixels;
        return heightPixels;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue/fontScale + 0.5f);

    }

    public static int sp2px(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue *fontScale + 0.5f);

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        Intent intent = new Intent();
        if(v == smart_cruise) {
            intent.setClass(HomeActivity.this, SmartActivity.class);
            startActivity(intent);
        } else if(v == through) {
            intent.setClass(HomeActivity.this, ThroughActivity.class);
            startActivity(intent);
        } else if(v == go_back) {
            intent.setClass(HomeActivity.this, GoBackActivity.class);
            startActivity(intent);
        } else if(v == setting) {
            intent.setClass(HomeActivity.this, SettingActivity.class);
            startActivity(intent);
        } else if(v == zhuye) {
            intent.setClass(HomeActivity.this, SmailActivity.class);
            startActivity(intent);
//            finish();
        }

    }

    @Override
    public String getClickAction(View v) {
        if(v == smart_cruise) {
            return "智能巡航";
        } else if( v == through) {
            return "直达模式";
        } else if(v == go_back) {
            return "往返模式";
        } else if(v == setting) {
            return "设置";
        } else if(v == zhuye) {
            return "进入动画";
        }
        return super.getClickAction(v);
    }


}

